package net.xfok.switches;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.preference.PreferenceManager;

public class ButtonSilent extends TButton
{

	private final static String INTENT_ACTION = "net.xfok.switches.ButtonSilent";
	private Intent _intent;

	public int getButtonBmp(Context context)
	{
		if (_intent != null)
		{
			int state = _intent.getIntExtra(AudioManager.EXTRA_RINGER_MODE, 2);
			_intent = null;
			if (state == AudioManager.RINGER_MODE_NORMAL)
				return R.drawable.silent_off;
			else
				return R.drawable.silent_on;
		}

		//If this method is call when not receiving a intent from android system,
		//Then invoke this block.
		AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
		int silentMode = audioManager.getRingerMode();
		if (silentMode == AudioManager.RINGER_MODE_NORMAL)
		{
//			Log.v("armNclover", "silent mode is enabled.");
			return R.drawable.silent_off;
		} else
		{
//			Log.v("armNclover", "silent mode is disabled.");
			return R.drawable.silent_on;
		}
	}

	@Override
	public void toggleSetting(Context context)
	{
		AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
		int silentMode = audioManager.getRingerMode();
		if(silentMode == AudioManager.RINGER_MODE_NORMAL)
			silentMode = AudioManager.RINGER_MODE_SILENT;
		else
			silentMode = AudioManager.RINGER_MODE_NORMAL;
		SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
		int vibrateMode = 1;
		boolean ringer_vibrate = sp.getBoolean("ringer_vibrate_on", true);
		boolean silent_vibrate = sp.getBoolean("silent_vibrate_on", true);
		if(ringer_vibrate)
		{
			if(silent_vibrate)
				vibrateMode = 1;
			else
				vibrateMode = 3;
		}else
		{
			if(silent_vibrate)
				vibrateMode = 2;
			else
				vibrateMode = 0;
		}
		audioManager.setRingerMode(silentMode);
		audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, vibrateMode);
	}

	@Override
	public String getIntentAction()
	{
		return INTENT_ACTION;
	}

	@Override
	public int canHandleIntent(Intent intent)
	{
		if (intent.getAction().equals(AudioManager.RINGER_MODE_CHANGED_ACTION))
		{
			_intent = intent;
			return ToggleWidget.HANDLING_TYPE_DONE;
		} else
		{
			return ToggleWidget.HANDLING_TYPE_UNABLE;
		}
	}
}
